import {create, deleteById, findOne, list, update} from '@/services/data-media-source-api';
import {PlusOutlined} from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable
} from '@ant-design/pro-components';
import {Button, Drawer, message, Modal, Space} from 'antd';
import React, {useRef, useState} from 'react';
import CreateOrUpdateForm from './components/CreateOrUpdateForm';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.AutoKeeperCluster) => {
  const hide = message.loading('正在添加');
  try {
    const res = await create({...fields});
    hide();
    if (res) {
      message.success('添加成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.AutoKeeperCluster) => {
  const hide = message.loading('更新中...');
  try {
    const res = await update(fields);
    hide();

    if (res) {
      message.success('更新成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};


const DataSource: React.FC = () => {

  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [createOrUpdateModalOpen, handleCreateOrUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [isCreate, handleIsCreate] = useState<boolean>(true);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.SeniorDataMediaSource>();

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.SeniorDataMediaSource) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      const res = await deleteById(selectedRows.id);
      hide();
      if (res) {
        message.success('删除成功');
        actionRef.current?.reload();
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  };
  const commonColumns: ProColumns<API.SeniorDataMediaSource>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      hideInSearch:true,
    },
    {
      title: '数据源名称',
      dataIndex: 'name'
    },
    {
      title: '类型',
      dataIndex: ['type'],
      hideInSearch: true,
    },
    {
      title: '编码',
      dataIndex: ['encode'],
      hideInSearch: true,
    },
    {
      title: 'URL',
      dataIndex: ['url'],
      hideInSearch: true,
    }
  ]

  const descriptionColumns: ProColumns<API.SeniorDataMediaSource>[] = [
    ...commonColumns,
  ];

  const columns: ProColumns<API.SeniorDataMediaSource>[] = [
    ...commonColumns,
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <Space>
            <a
              key="detail"
              onClick={() => {
                setCurrentRow(record);
                setShowDetail(true);
              }}
            >
              查看
            </a>
            <a
              key="edit"
              onClick={() => {
                handleCreateOrUpdateModalOpen(true);
                handleIsCreate(false);
                setCurrentRow(record);
              }}
            >
              编辑
            </a>
            {!record?.used && (
              <a
                type='button'
                key="delete"
                onClick={() => {
                  Modal.confirm({title: '确实删除?', onOk: () => handleRemove(record)});
                }}
              >删除
              </a>
            )}
          </Space>
        )
      }

    }
  ];

  return (
    <PageContainer>
      <ProTable<API.SeniorDataMediaSource, API.PageParams>
        headerTitle='数据源列表'
        actionRef={actionRef}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleIsCreate(true);
              handleCreateOrUpdateModalOpen(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={list}
        columns={columns}
      />
      <CreateOrUpdateForm
        onSubmit={async (value) => {
          let success;
          if (currentRow?.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleCreateOrUpdateModalOpen(false);
            setCurrentRow(undefined);
            await actionRef?.current?.reload();
            return true;
          }
          return false;
        }}
        title={isCreate ? '新建' : '编辑'}
        onCancel={() => {
          handleCreateOrUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={createOrUpdateModalOpen}
        values={currentRow}
      />

      <Drawer
        width={500}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<API.SeniorDataMediaSource>
            column={1}
            title={currentRow?.name}
            request={async () => findOne(currentRow?.id)}
            params={{
              id: currentRow?.id,
            }}
            columns={descriptionColumns as ProDescriptionsItemProps<API.SeniorDataMediaSource>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default DataSource;
